package cn.est.service.impl;

import cn.est.constants.Constants;
import cn.est.exceptions.RedisException;
import cn.est.exceptions.TokenProtectedException;
import cn.est.pojo.Users;
import cn.est.service.TokenService;
import cn.est.utils.RedisUtil;
import cn.est.vo.TokenVo;
import cn.est.vo.WxTokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    RedisUtil redisUtil;

    @Override
    public TokenVo genenrateToken(Users users) {
        Long gentime=System.currentTimeMillis();
        //String tokenkey="token:"+System.currentTimeMillis()+"-"+MD5Utils.MD5(users.getAccount()).substring(26)+"-"+users.getAccount();
        String account=users.getAccount()!=null?users.getAccount():users.getOpenId();
        System.out.println(account);
        String tokenkey="token:pc-"+gentime+"-"+ UUID.randomUUID().toString().replace("-","").substring(26) +"-"+account;
        TokenVo tokenVo=new TokenVo();
        tokenVo.setCreateTime(gentime);
        tokenVo.setToken(tokenkey);
        tokenVo.setOverTime(gentime+Constants.Token.VALID_TIME);
        return tokenVo;

    }

    @Override
    public TokenVo refreshToken(String oldToken) throws RedisException, TokenProtectedException {
        //1.有效性效验，效验redis中有没有token
            if (!redisUtil.hasKey(oldToken)){
                throw new RedisException("redis不存在token，过期了,请从新登录");
            }
        //2.oldToken是否没有达到有效验证时间，替换时间是有效时间的前5分钟
        String oldTokenTime=oldToken.split("-")[1];
            if (System.currentTimeMillis()-Long.parseLong(oldTokenTime)<Constants.Token.VALID_TIME-Constants.Token.NO_PROTEST_TIME){
                throw new TokenProtectedException("token还在保护期，不允许替换");
            }
        //3.生成新的token
        Users users= (Users) redisUtil.get(oldToken);
        TokenVo tokenVo=genenrateToken(users);
        //4.获取微信accesstoken
        Object o=redisUtil.get(tokenVo.getToken());
        if (o!=null) {
            WxTokenVo wxTokenVo = (WxTokenVo)o;
            wxTokenVo.setTokenVo(tokenVo);
            redisUtil.set("wx:" + tokenVo.getToken(), wxTokenVo, Constants.Token.WX_VALID_TIME);
        }
        //4.新旧token替换
        saveToken(tokenVo.getToken(),users);
        //5.old Token续命2分钟
        redisUtil.set(oldToken,users,Constants.Token.DELAY_TIME);

        return tokenVo;

    }

    @Override
    public void saveToken(String token, Users users) {
        redisUtil.set(token,users, Constants.Duration.HALF_AN_HOUR);
    }

    public static void main(String[] args) {
        String token="token:pc-1618046541242-7ab247-15018526841";
        System.out.println(token.split("-")[1]);
    }
}
